package cn.com.cetccst.appstore;

import static cn.com.cetccst.appstore.kv.AppStoreKV.kvStore;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;

import org.jetbrains.annotations.Contract;
import org.slf4j.Logger;

import cn.com.cetccst.appstore.database.AppStoreRepository;
import cn.com.cetccst.appstore.kv.AppStoreKV;
import cn.com.cetccst.appstore.kv.KVKeys;
import cn.com.cetccst.appstore.log.AppStoreLogger;
import cn.com.cetccst.appstore.network.AppStoreHttpRequester;
import cn.com.cetccst.appstore.receiver.PackageInstallerReceiver;
import cn.com.cetccst.kvmanager.IKVStore;

public class AppStoreManager {

    private static AppStoreManager instance;

    @Contract(pure = true)
    private AppStoreManager(){}

    public static void initialize(Context context) {
        AppStoreLogger.initialize(context);
        AppStoreKV.initialize(context);
        AppStoreRepository.initialize(context);
        if (!TextUtils.isEmpty(kvStore.decodeString(KVKeys.KEY_BASE_URL))) {
            AppStoreHttpRequester.initialize(context, kvStore.decodeString(KVKeys.KEY_BASE_URL));
        }

        registerReceiver(context);

        instance = new AppStoreManager();
    }

    private static void registerReceiver(Context context) {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_PACKAGE_ADDED);
        filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
        filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
        filter.addDataScheme("package");
        context.registerReceiver(new PackageInstallerReceiver(), filter);
    }

    public static AppStoreManager get() {
        return instance;
    }

    /**
     * 可以指定接入SDK的日志输入的目录
     *
     * @param logger
     */
    public static void setLogger(Logger logger) {
        AppStoreLogger.setLogger(logger);
    }

    /**
     * 可以指定接入的KV实例
     *
     * @param kv
     */
    public static void setKVStore(IKVStore kv) {
        kvStore = kv;
    }
}
